import axios,{ type AxiosResponse , type AxiosRequestHeaders } from 'axios'
import { log } from 'console';
import { showSuccessToast, showFailToast } from 'vant';
import { useUserInfoStore } from '../store/userInfo'
interface RequestModel<T> {
  code:string | number
  data:T
  message?:string
}

const request = axios.create({
  baseURL: "/api",
  timeout:5000
})

request.interceptors.request.use(
  (config) => {
    const userInfoStore = useUserInfoStore()
    if(userInfoStore.token) {
      config.headers.token = userInfoStore.token
    }
    return config
  }
)

request.interceptors.response.use(
  async (response: AxiosResponse<RequestModel<any> >) => {
    const res = response.data;
    
    if(res.code == 200 || res.code == '200') {
      return res.data
    } else {
      console.log('接口code不是200');
      
    }
  },
  (error) => {
		// 对响应错误做点什么
		if (error.message.indexOf('timeout') != -1) {
			showFailToast('网络超时');
		} else if (error.message == 'Network Error') {
			showFailToast('网络连接错误');
		} else {
			if (error.response.data) showFailToast(error.response.statusText);
			else showFailToast('接口路径找不到');
		}
		return Promise.reject(error);
	}
)


export default request